package com.dc.wifi.main.utils;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Handler;

import com.dc.wifi.R;

import java.io.IOException;

public class AudioPlayerUtil {
    private MediaPlayer mediaPlayer;
    private Handler handler = new Handler();
    private Runnable playRunnable;
    private long interval = 2000; // 默认间隔时间为2秒
    private boolean isPlaying = false;
    private Context context;

    public AudioPlayerUtil(Context context) {
        this.context = context;
        initMediaPlayer();
    }

    private void initMediaPlayer() {
        mediaPlayer = new MediaPlayer();
        AssetFileDescriptor afd = context.getResources().openRawResourceFd(R.raw.zzzz);
        try {
            mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
            afd.close();
            mediaPlayer.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void play(long loopInterval) {
        if (isPlaying) {
            stop();
        }
        interval = loopInterval;
        isPlaying = true;
        mediaPlayer.start();
        playRunnable = new Runnable() {
            @Override
            public void run() {
                if (isPlaying) {
                    if (!mediaPlayer.isPlaying()) {
                        mediaPlayer.seekTo(0);
                        mediaPlayer.start();
                    }
                    handler.postDelayed(this, interval);
                }
            }
        };
        handler.postDelayed(playRunnable, interval);
    }

    public void stop() {
        isPlaying = false;
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
            mediaPlayer.seekTo(0);
        }
        handler.removeCallbacks(playRunnable);
    }

    public void setInterval(long newInterval) {
        this.interval = newInterval;
        if (isPlaying) {
            handler.removeCallbacks(playRunnable);
            handler.postDelayed(playRunnable, interval);
        }
    }
}